/*********************************************************************\
*
*                  (c) lkc
*                  All Rights Reserved. lkc Confidential
*
\*********************************************************************/
/*********************************************************************\
*   Title                      :
*
*   Module Description         :
*
*   Author                     : lkc
*
*   Created                    : 2018-6-24
*
\*********************************************************************/
#ifndef V4L2_DEVICE_H
#define V4L2_DEVICE_H

#include <opencv2/opencv.hpp>
#include <mutex>
#include <linux/videodev2.h>


struct m_testbuffer
{
    unsigned char *start;
    size_t offset;
    unsigned int length;
};

class V4l2Device
{
public:
    void StartReadFrame();
    bool GetFrame(v4l2_buffer &buf, cv::Mat &matFrame);
    bool GetFrame(v4l2_buffer &buf);
    void ReleaseBuf(v4l2_buffer &buf);

    V4l2Device(const std::string devName);
    ~V4l2Device();

private:
    bool Init();
    bool InitMmap();
    bool InitDevice();
    bool OpenDevice();
    void CloseDevice();
    bool Dqbuf(v4l2_buffer &buf);
    bool DequeueBuf();
    bool Qbuf(v4l2_buffer &buf);
    void Qbufs();

private:
    const static int BUF_NUM = 5;
    int m_bufRefCount[BUF_NUM];//数组每一项记录取出的每一个帧缓存的被引用次数
    std::mutex m_bufRefCountMtx[BUF_NUM];//一个线程正在使用引用计数时，其他线程不能修改
    std::vector<v4l2_buffer> m_dqedBufs;//m_dqedBufs容器存放从FIFO输出队列中取出的帧缓存
    std::mutex m_dqedBufsMtx;//m_dqedBufs容器锁，一个线程正在使用m_dqedBufs存容器时，其他线程不能修改
    std:: string m_devName;
    int m_fdV4l;
    unsigned int m_frameWidth;
    unsigned int m_frameHeight;
    bool m_isBufferHasData = false;
    struct m_testbuffer m_mmapMemorys[BUF_NUM];
};
extern V4l2Device v4lDev;
#endif // V4L2_DEVICE_H

/********************************************************************\
 *
 * REVISION RECORDS
 *
\*********************************************************************/
/*********************************************************************/
/*
 *
 *
 *
\*********************************************************************/
/*------------------------------The End------------------------------*/
